package com.qy.wap.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;

import com.qy.util.Constant;
import com.qy.util.XmlReader;

//http://119.161.210.49:6188/qywapwar/xmlReaderServlet?action=createTable&fileName=e:/testxmlfiles/test.xml
//http://119.161.210.49:6188/qywapwar/xmlReaderServlet?action=insertData&fileName=e:/zhangTmp/scan_data.xml&tableName=Login_1

public class XmlReaderServlet extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		XmlReader xmlReader = new XmlReader();
		try {
			String action = req.getParameter("action");
			String fileName = req.getParameter("fileName");
			List<String> sqls = null;
			if ("createTable".equals(action) && fileName != null) {
				sqls = xmlReader.getCreateSql(req.getParameter("fileName"));
			} else if ("insertData".equals(action) && fileName != null) {
				String tableName = req.getParameter("tableName");
				if(tableName == null)
					tableName = "tmpTableName";
				sqls = xmlReader.getInsertSql(tableName,fileName);
			}else
			{
				resp.getWriter().println("invalid parameter");
			}
			if (sqls != null) {
				if(sqls.size() == 0)
				{
					resp.getWriter().println("sql size is 0" );
				}else
				{
					String sql = "";
					try {
						Connection con = Constant.getCon();
						Statement stmt = con.createStatement();
						for (int i = 0; i < sqls.size(); i++) {
							sql = sqls.get(i);
							stmt.execute(sql);
						}
						resp.getWriter().println("OK");
					} catch (Exception e) {
						resp.getWriter().println(e.getMessage());
						resp.getWriter().println("sql:" + sql);
						e.printStackTrace();
					}
				}
			}
		} catch (DocumentException e) {
			resp.getWriter().println(e.getMessage());
			e.printStackTrace();
		}
	}
}
